/*
Word Search

Given a 2D board and a word, find if the word exists in the grid.

The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once.

For example,
Given board =

[
["ABCE"],
["SFCS"],
["ADEE"]
]
word = "ABCCED", -> returns true,
word = "SEE", -> returns true,
word = "ABCB", -> returns false.
*/
#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

class Solution {
public:
	int dir[4][2] = { { -1, 0 }, { 1, 0 }, { 0, -1 }, { 0, 1 } };
	bool findPath(vector<vector<char> > &board, string& word, vector<vector<bool> >& used, int curX, int curY, int curIdx)
	{
		int n = board.size();
		int m = board[curX].size();
		if (curIdx == word.size()) return true;
		for (int k = 0; k < 4; ++k)
		{
			int newX = curX + dir[k][0];
			int newY = curY + dir[k][1];
			if (newX >= 0 && newX < n && newY >= 0 && newY < m && used[newX][newY] == false && board[newX][newY] == word[curIdx])
			{
				used[newX][newY] = true;
				if (findPath(board, word, used, newX, newY, curIdx + 1)) return true;
				used[newX][newY] = false;
			}
		}
		return false;
	}
	bool exist(vector<vector<char> > &board, string word) {
		// Start typing your C/C++ solution below  
		// DO NOT write int main() function  
		if (word.size() == 0) return true;
		int n = board.size();
		if (n == 0) return false;
		int m = board[0].size();

		vector<vector<bool> > used(n, vector<bool>(n, false));
		for (int i = 0; i < board.size(); ++i)
		{
			for (int j = 0; j < board[i].size(); ++j)
			{
				if (board[i][j] == word[0])
				{
					used[i][j] = true;
					if (findPath(board, word, used, i, j, 1)) return true;
					used[i][j] = false;
				}
			}
		}
		return false;
	}
};

int main()
{
	cout << "Word Search:  " << endl;

	
	char c11[] = "CAA";
	char c12[] = "AAA";
	char c13[] = "BCD";

	string word = "AAB";

	

	vector<vector<char> > board;
	vector<char> temp1(c11, c11+sizeof(c11)/sizeof(char)-1);
	vector<char> temp2(c12, c12 + sizeof(c12) / sizeof(char)-1);
	vector<char> temp3(c13, c13 + sizeof(c13) / sizeof(char)-1);
	board.push_back(temp1);
	board.push_back(temp2);
	board.push_back(temp3);

	Solution s;

	bool flag = s.exist(board,word);
	if (flag)
	{
		cout <<"True" << endl;
	}
	else
	{
		cout << "False"<< endl;
	}

	system("pause");

	return 0;
}